package com.doone.telmarket.action.admin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;

import com.doone.telmarket.domain.Activity;
import com.doone.telmarket.domain.ActivityOrder;
import com.doone.telmarket.service.ActivityOperation;
import com.doone.telmarket.service.SiteResourceManager;
import com.opensymphony.xwork2.ActionContext;

/**
 * @package com.doone.telmarket.action.admin
 * @author 甘雨波
 * @description 精彩促销推荐
 * @date 2009-10-26
 */
public class ActivityAction extends BaseActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Logger log = Logger.getLogger(ServiceAction.class);

	@Autowired
	private ActivityOperation remoteActivityOperation;

	private String errorMessage;
	private String page;
	private String updateType;

	private File file;
	private String imageName;
	private String orderId;
	private String activityId;
	private String title;
	private String content;
	private String url;
	private String person;
	private String begin;
	private String end;
	private File[] upload;
	private String[] uploadFileName;
	private String id;
	private String errorMsg;

	@Autowired
	private SiteResourceManager siteResourceManager;

	@SuppressWarnings("static-access")
	@Action("getAllActivity")
	public void getAllActivity() {
		try {
			//log.info("查询精彩促销");

			List<Activity> list = remoteActivityOperation.selectActivity();
			//log.info("查询精彩促销"+list.size());
			JSONUtil json = new JSONUtil();
			responseWrite(json.serialize(list));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("获取数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	@Action(value = "selectActivity2", results = { @Result(name = "success", location = "/admin/modifyActivity.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String selectActivity2() {
		try {
			//log.info("查询精彩促销");

			List<Activity> list = remoteActivityOperation.selectActivity();
			//log.info("查询精彩促销"+list.size());
			session.put("list", list);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			errorMessage = "获取数据失败";
			return "error";
		}

	}

	@Action(value = "deleteActivity", results = { @Result(name = "success", location = "/admin/success.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String deleteActivity() {
		try {
			remoteActivityOperation.deleteActivity(Integer.parseInt(id));
			page = "selectActivity2";
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			errorMsg = "删除活动失败";
			return "error";
		}
	}

	@Action("selectActivityAjax")
	public void selectActivityAjax() {
		try {
			//log.info("查询精彩促销");
			List<Activity> list = remoteActivityOperation.selectActivity();
			//log.info("查询精彩促销"+list.size());
			responseWrite(JSONUtil.serialize(list));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("获取数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	@Action(value = "updateImage", interceptorRefs = { @InterceptorRef("fileUploadStack") })
	public void updateImage() throws IOException {
		try {
			//log.info("imageName>" + imageName);
			siteResourceManager.uploadFile(file, imageName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Action("deleteActivityOrder")
	public void deleteActivityOrder() {
		try {
			remoteActivityOperation.deleteActivityOrder();
			responseWrite("删除数据成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("删除数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	@Action("insertActivityOrder")
	public void insertActivityOrder() {
		try {
			ActivityOrder a = new ActivityOrder();
			a.setId(Integer.parseInt(id));
			a.setOrderId(Integer.parseInt(orderId));
			a.setActivityId(Integer.parseInt(activityId));
			remoteActivityOperation.insertActivityOrder(a);
			responseWrite("保存数据成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("保存数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	@Action("selectActivityOrder")
	public void selectActivityOrder() {
		try {
			//log.info("查询精彩促销");
			List<Activity> list = remoteActivityOperation.selectActivityOrder();
			//log.info("查询精彩促销"+list.size());
			responseWrite(JSONUtil.serialize(list));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("获取数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	@Action("saveOperation")
	public void saveOperation() {
		try {
			ActionContext ac = ActionContext.getContext();
			HttpServletRequest sr = (HttpServletRequest) ac.get(StrutsStatics.HTTP_REQUEST);
			StringBuffer pagePath = new StringBuffer();
			pagePath.append("http://");
			pagePath.append(sr.getServerName());
			pagePath.append(":");
			pagePath.append(sr.getLocalPort());
			pagePath.append("/");
			pagePath.append(sr.getContextPath());
			pagePath.append("/admin/templete/activity.jsp");

			ServletContext sc = (ServletContext) ac.get(StrutsStatics.SERVLET_CONTEXT);
			String path = sc.getRealPath("/");
			generatePage(path, pagePath.toString());

			responseWrite("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("保存失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	@Action(value = "saveActivity", interceptorRefs = { @InterceptorRef("fileUploadStack") }, results = {
			@Result(name = "success", location = "/admin/success.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String saveActivity() {
		try {
			if ("/".equals(url.substring(url.length() - 1, url.length()))) {
				url = url.substring(0, url.length() - 1);
			}
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
			Activity activity = new Activity();
			activity.setTitle(title);
			activity.setContent(content);
			activity.setUrl(url);
			activity.setPerson(person);
			activity.setBegin(s.parse(begin));
			activity.setEnd(s.parse(end));
			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			//log.info("message:" + upload);
			this.getUpload();
			siteResourceManager.uploadFile(upload[0], "/images/service/small" + dateStr + ".jpg");
			siteResourceManager.uploadFile(upload[1], "/images/service/big" + dateStr + ".jpg");
			activity.setImagePath("/images/service/small" + dateStr + ".jpg");
			activity.setBigImage("/images/service/big" + dateStr + ".jpg");
			remoteActivityOperation.saveActivity(activity);
			page = "setPromotion.jsp";
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			errorMsg = "保存活动信息失败";
			return "error";
		}

	}

	/**
	 * @return
	 */
	@Action(value = "selectActivityById", interceptorRefs = { @InterceptorRef("fileUploadStack") }, results = {
			@Result(name = "success", location = "/admin/modActivity.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String queryActivityById() {
		try {
			Activity activity = remoteActivityOperation.selectById(Integer.parseInt(id));
			page = "selectActivity2";
			session.put("activity", activity);
			//	log.info("开始时间为：" + activity.getBegin());
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			errorMsg = "获取数据失败";
			return "error";
		}
	}

	@Action(value = "updateActivity", interceptorRefs = { @InterceptorRef("fileUploadStack") }, results = {
			@Result(name = "success", location = "/admin/success.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String updateActivity() {
		try {
			if ("/".equals(url.substring(url.length() - 1, url.length()))) {
				url = url.substring(0, url.length() - 1);
			}
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
			Activity a = new Activity();
			a.setId(Integer.parseInt(id));
			a.setTitle(title);
			a.setContent(content);
			a.setPerson(person);
			a.setBegin(s.parse(begin));
			a.setEnd(s.parse(end));
			a.setUrl(url);
			remoteActivityOperation.updateActivity(a);
			page = "selectActivity2";
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			errorMsg = "更新活动失败";
			return "error";
		}
	}

	private void generatePage(String rootPath, String pagePath) throws IOException {
		siteResourceManager.writePage(pagePath, rootPath + "/web/common/activity.html");
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getUpdateType() {
		return updateType;
	}

	public void setUpdateType(String updateType) {
		this.updateType = updateType;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getPerson() {
		return person;
	}

	public void setPerson(String person) {
		this.person = person;
	}

	public String getBegin() {
		return begin;
	}

	public void setBegin(String begin) {
		this.begin = begin;
	}

	public String getEnd() {
		return end;
	}

	public void setEnd(String end) {
		this.end = end;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getImageName() {
		return imageName;
	}

	public void setImageName(String imageName) {
		this.imageName = imageName;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getActivityId() {
		return activityId;
	}

	public void setActivityId(String activityId) {
		this.activityId = activityId;
	}

}
